package com.woniuxy.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.entity.ResponseResult;
import com.woniuxy.security.util.JwtToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

public class JwtFilter extends AuthenticatingFilter {
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        String token = ((HttpServletRequest) request).getHeader("Authorization");
        return new JwtToken(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            boolean isAllowed = executeLogin(request,response);
            if (isAllowed){
                response.getWriter().write(new ObjectMapper().writeValueAsString(ResponseResult.SUCCESS));
                return true;
            }else{
                response.getWriter().write(new ObjectMapper().writeValueAsString(ResponseResult.FAIL));
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return isAccessAllowed(request,response,mappedValue);
    }
}
